<template>
  <div class="env-container">
    <h1>环境切换与代理助手</h1>
    <!-- 当前环境
    环境1
        名称    编辑 切换 删除
        当前地址
        代理地址
    添加/保存环境 
    -->
    <div class="current-env">
      <span>
        当前环境：
        <span id="current-env-name">{{
          currentEnv.name
            ? currentEnv.name + " -- " + currentEnv?.target?.name
            : "未选择"
        }}</span>
      </span>
      <i
        v-if="currentEnv.name"
        class="el-icon-delete"
        @click="removeCurrentEnv()"
      ></i>
    </div>

    <el-card
      v-for="(item, index) in envs"
      class="box-card"
      :key="index"
      :class="{ active: currentCardIndex == index }"
      @click.native="switchCard(index)"
    >
      <div slot="header">
        <div class="env-item-header">
          <div class="env-name">{{ item.name }}</div>
          <div class="env-item-actions">
            <el-button
              type="success"
              icon="el-icon-check"
              circle
              size="small"
              @click="switchEnv(index)"
            >
            </el-button>
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              size="small"
              @click="editEnv(index)"
            >
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              size="small"
              @click="removeEnv(index)"
            ></el-button>
          </div>
        </div>

        <div class="env-now-url">
          当前地址
          {{ item.url }}
        </div>
      </div>
      <div>
        <el-collapse>
          <el-collapse-item
            title="选择代理地址"
            name="1"
            :disabled="currentCardIndex != index"
          >
            <!-- 当前地址 -->

            <el-radio
              v-model="targetRadio"
              v-for="(env, i) in item.targets"
              :label="i"
              :value="i"
              @click.stop="changeTarget(i)"
              @change.stop="changeTarget(i)"
            >
              <div class="env-target-url">
                {{ env.name }}
                {{ env.url }}
              </div></el-radio
            ></el-collapse-item
          >
        </el-collapse>
      </div>
    </el-card>
    <el-form
      v-if="operationType"
      ref="envFormRef"
      :model="envForm"
      label-width="100px"
    >
      <div class="name-container">
        <div class="current-item align-con">
          <el-input
            size="small"
            v-model="envForm.name"
            placeholder="环境名称：（如：本地开发）"
          ></el-input>
          <el-input
            size="small"
            v-model="envForm.url"
            placeholder="当前请求地址：（如：http://localhost:8080）"
          ></el-input>
        </div>
      </div>
      <el-divider></el-divider>
      <div v-for="(item, i) in envForm.targets" class="target-item align-con">
        <div class="align-con">
          <el-input
            size="small"
            v-model="item.name"
            placeholder="目标地址名称"
          ></el-input>
          <el-input
            size="small"
            v-model="item.url"
            placeholder="目标地址"
          ></el-input>
        </div>
        <el-button
          v-if="i > 0"
          type="danger"
          icon="el-icon-delete"
          size="small"
          @click="removeTarget(index)"
        ></el-button>
        <el-button
          v-else
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="addTarget"
        >
        </el-button>
      </div>
    </el-form>

    <el-button
      class="add-btn"
      size="small"
      type="success"
      color="#4CAF50"
      @click="addEnv"
      >{{ operationType ? "保存环境" : "添加环境" }}
    </el-button>
  </div>
</template>

<script>
export default {
  name: "",
  components: {},
  data() {
    return {
      operationType: "", // 操作类型 add edit
      targetRadio: "1",

      currentCardIndex: "0",
      currentEnv: "",
      envForm: {
        name: "",
        url: "",
        targets: [{ name: "", url: "" }],
      },
      envs: [
        {
          name: "ams",
          url: "http://192.168.1.1:8080",
          targets: [
            { name: "代理地址1", url: "http://192.168.1.1:8081" },
            { name: "代理地址2", url: "http://192.168.1.1:8082" },
            { name: "代理地址3", url: "http://192.168.1.1:8083" },
          ],
        },
        {
          name: "gms",
          url: "http://192.168.1.1:8080",
          targets: [{ name: "代理地址1", url: "http://192.168.1.1:8081" }],
        },
      ],
    };
  },
  mounted() {
    this.loadEnvs();
  },
  methods: {
    // 加载保存的环境配置
    loadEnvs() {
      chrome.storage.local.get(["envs", "currentEnv"], (result) => {
        this.envs = result.envs || [];
        const currentEnv = result.currentEnv;
        this.currentEnv = {};
        this.targetRadio = 0;
        this.currentCardIndex = 0;
        if (currentEnv) {
          this.currentEnv = currentEnv;
          this.targetRadio = 0;
          this.envs.forEach((env, index) => {
            if (env.name === currentEnv.name) {
              this.currentCardIndex = index;
            }
          });
          currentEnv.targets.forEach((data, i) => {
            if (currentEnv.target?.name) {
              if (currentEnv.target?.name == data.name) {
                this.targetRadio = i;
              }
            }
          });
        }
      });
    },
    //初始化内容
    initData() {
      this.envForm = {
        name: "",
        url: "",
        targets: [{ name: "", url: "" }],
      };
    },
    addEnv() {
      if (this.operationType) {
        if (!this.envForm.name || !this.envForm.url) {
          alert("请输入环境名称和url");
          return;
        }
        chrome.storage.local.get("envs", (result) => {
          if (this.operationType == "edit") {
            this.envs.splice(this.currentCardIndex, 1, this.envForm);
          } else {
            let nameList = this.envs.map((env) => {
              return env.name;
            });
            if (nameList.includes(this.envForm.name)) {
              alert("环境名称已存在");
              return;
            }
            this.envs.push(this.envForm);
          }
          chrome.storage.local.set({ envs: this.envs }, () => {
            console.log("st--success");
            alert("保存成功");
            // 清空输入框
            this.initData();
            this.loadEnvs(); // 重新加载列表
            this.operationType = "";
          });
        });
      } else {
        this.operationType = "add";
      }
    },
    // 添加代理
    addTarget() {
      let target = {
        name: "",
        url: "",
      };
      let targets = this.envForm.targets;
      targets.push(target);
      this.$set(this.envForm, "targets", targets);
    },
    changeTarget() {},
    //切换卡片
    switchCard(index) {
      //
      let currentEnv = this.currentEnv;
      if (!currentEnv || currentEnv.name != this.envs[index].name) {
        this.targetRadio = 0;
      }
      this.currentCardIndex = index;
    },
    //切换环境
    switchEnv(index) {
      this.currentEnv = this.envs[index];
      let env = this.envs[index];
      env.target = env.targets[this.targetRadio];

      // 保存当前环境
      chrome.storage.local.set({ currentEnv: env }, () => {
        // 保存当前环境到本地存储（供下次页面加载时提前注入）
        // 通知background更新规则和注入脚本
        chrome.runtime.sendMessage(
          {
            action: "switchEnv",
            env: env,
          },
          (response) => {
            console.log(response);

            if (response.success) {
              this.loadEnvs(); // 重新加载列表显示当前环境
              alert(`已切换至【${env.name}】`);
              // 强制刷新页面，让提前注入的脚本生效
              chrome.tabs.query(
                { active: true, currentWindow: true },
                (tabs) => {
                  chrome.tabs.reload(tabs[0].id);
                }
              );
            } else {
              alert("切换失败，请重试");
            }
          }
        );
      });
    },
    //编辑环境
    editEnv(index) {
      this.operationType = "edit";
      this.envForm = this.envs[index];
    },
    //删除环境
    removeEnv(index) {
      this.envs.splice(index, 1);
      // 如果删除的是当前环境，清除当前环境
      if (
        this.envs.findIndex((env) => env.url === this.currentEnv.url) === -1
      ) {
        this.currentEnv = {};
        chrome.storage.local.set({ currentEnv: null });
      }
      chrome.storage.local.set({ envs: this.envs }, this.loadEnvs);
    },
    removeTarget(index) {
      let arr = this.envForm.targets;
      arr.splice(index, 1);
      this.$set(this.envForm, "targets", arr);
    },
    // 删掉当前chrome插件环境
    removeCurrentEnv() {
      chrome.storage.local.remove("currentEnv", () => {
        this.loadEnvs();
        // 通知插件环境已删除
        chrome.runtime.sendMessage({ action: "removeEnv" });
        alert("当前环境已删除");
      });
    },
  },
};
</script>
<style lang="scss" scoped>
h1,
ul,
li,
dl,
dt,
dd {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  width: 100%;
}

.env-container {
  user-select: none;
  width: 400px;
  padding: 15px;
  font-family: Arial, sans-serif;
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: center;
  border: 1px solid #ddd;
  //   background-color: #121212;
  //   color: white;
  font-size: 14px;
  border-radius: 4px;
  h1 {
    text-align: center;
    margin-bottom: 14px;
    color: #4285f4;
  }

  .current-env {
    min-width: 350px;
    padding: 5px;
    background: #f0f7ff;
    border-left: 3px solid #4285f4;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    color: #333;
  }
  .el-card {
    font-size: 12px;
    width: 100%;
    margin-bottom: 8px;
    // 选择状态

    ::v-deep {
      .el-card__body,
      .el-card__header {
        padding: 6px 8px;
      }
      .el-collapse-item__header,
      .el-collapse {
        border: none;
      }
      .el-collapse-item__header {
        height: 26px;
        line-height: 26px;
      }
      .el-collapse-item__content {
        padding-bottom: 0px;
      }
    }
    .el-button {
      height: 20px;
      width: 20px;
      padding: 0 0px;
      line-height: 20px;
      font-size: 12px;
      margin-left: 4px;
    }
    .el-radio {
      font-size: 12px !important;
      align-items: center;
      display: flex;
      margin-bottom: 8px;
    }
    .env-now-url,
    .env-target-url {
      display: flex;
      font-size: 12px !important;
    }
  }
  .active {
    border: 1px solid #589ef8;
  }
  .env-item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  //   .el-button {
  //     height: 20px;

  //     padding: 0 4px;
  //     line-height: 20px;
  //     font-size: 12px;
  //   }
  .align-con {
    display: flex;
    align-items: center;
    .el-button {
      height: 20px;

      padding: 0 4px;
      line-height: 20px;
      font-size: 12px;
      margin-left: 4px;
    }
    .el-input:first-child {
      width: 40%;
    }
  }
  .current-item {
    background-color: #f5f7fa;
    // margin-bottom: 14px;
  }
  .el-divider--horizontal {
    margin: 10px 0;
  }
  .target-item {
    margin-bottom: 8px;
  }
}
</style>
